﻿using Cms.Application.Admin.Views;
using Cms.Application.IO;
using Cms.Data;
using Cms.Domain;
using Cms.Domain.RepositoryInterfaces;

namespace Cms.Application.Admin.Presenters
{
    public class PluginTemplatesPresenter : BasePresenter
    {
        private readonly Administrator _administrator;
        private readonly IPluginTemplatesView _view;
        public IDiskAccess DiskAccess;

        public PluginTemplatesPresenter(IPluginTemplatesView view)
            : this(view, new RepositoryFactory())
        {
            DiskAccess = new DiskAccess();
        }

        public PluginTemplatesPresenter(IPluginTemplatesView view, IRepositoryFactory repositoryFactory)
            : base(view, repositoryFactory)
        {
            _view = view;
            _administrator = AdministratorRepository.GetAdministrator(_view.AdministratorID);
            var plugin = (TemplatablePlugin)SystemRepository.GetPlugin(_view.PluginID);
            _view.SetHeading(Translator.GetText("Admin/Translations/Plugins/" + plugin.GetClassName() + ".xml",
                                                "PluginName", _view.Localization));
            if (!_administrator.HasPermission.PluginTemplates)
                _view.RedirectToPermissionDeniedPage();
        }

        public void Initialize()
        {
            SetPluginTemplates();
        }
        
        public void SetPluginTemplates()
        {
            var plugin = (TemplatablePlugin)SystemRepository.GetPlugin(_view.PluginID);
            _view.SetPluginTemplates(plugin.GetTemplates(_administrator.CurrentSite.ID));
        }
        
        public void DeleteTemplate(int id)
        {
            PluginTemplate template = SystemRepository.GetPluginTemplate(id);
            var plugin = (TemplatablePlugin)template.Plugin;
            plugin.Templates.Remove(template);
            template.Plugin = null;
            template.Site = null;
            SystemRepository.SavePlugin(plugin);
            DiskAccess.DeleteFile("__System\\PluginTemplates\\" + id + ".ascx");
            SetPluginTemplates();
        }
    }
}